const { default: BigNumber } = require('bignumber.js');
const Base = require('./base.js');
const moment = require('moment');
const { think } = require('thinkjs');

module.exports = class extends Base {
  async importListAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    let has = false;

    const query = this.get();
    query.type = 1;
    if (query.status == 2) {
      query.status = ['IN', [2, 3]];
    }

    if (!think.isEmpty(query.has)) {
      has = true;
      delete query.has;
    }

    if (query.title) {
      query.title = ['like', `%${query.title}%`];
    }

    delete query.page;
    delete query.size;

    const data = await this.model('contract_list')
      .where(query)
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      // console.log(item, 888);
      // if (item.file) {
      //   item.file = JSON.parse(item.file);
      // }
      item.qixian = [item.date_start, item.date_end];
      item.mianzu = [item.mianzu_start, item.mianzu_end];
      if (item.project) {
        item.project_id = JSON.parse(item.project);
      }

      if (has) {
        item.has =
          (await this.model('income_list')
            .where({
              contract_id: item.id,
              type: ['IN', ['fangzu', 'wuye', 'yajin']],
              status: 1,
            })
            .sum('money')) || 0;
      }

      if (item.custom_info) {
        item.custom = JSON.parse(item.custom_info);
      }
      item.months = moment(item.date_end)
        .add(1, 'days')
        .diff(moment(item.date_start), 'month');
    }

    return this.success(data);
  }

  async importListTypeAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    let query;

    if (this.get('getType') == 2) {
      query = {
        type: 1,
        status: 1,
        date_end: [
          'between',
          moment().format('YYYY-MM-DD'),
          moment()
            .add(6, 'months')
            .format('YYYY-MM-DD'),
        ],
      };
    }

    if (this.get('getType') == 1) {
      query = {
        type: 1,
        status: 2,
      };
    }

    const data = await this.model('contract_list')
      .where(query)
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      // if (item.file) {
      //   item.file = JSON.parse(item.file);
      // }
      item.qixian = [item.date_start, item.date_end];
      item.mianzu = [item.mianzu_start, item.mianzu_end];
      item.project_id = JSON.parse(item.project);
      if (item.custom_info) {
        item.custom = JSON.parse(item.custom_info);
      }
      item.months = moment(item.date_end)
        .add(1, 'days')
        .diff(moment(item.date_start), 'month');
    }

    return this.success(data);
  }

  async outputListAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get();
    query.type = 2;

    if (query.project_name) {
      query.project_id = query.project_name;
      delete query.project_name;
    }

    delete query.page;
    delete query.size;

    const data = await this.model('contract_list')
      .where(query)
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      // item.project_id = JSON.parse(item.project);
      item.qixian = [item.date_start, item.date_end];
      item.mianzu = [item.mianzu_start, item.mianzu_end];
      item.project_name = item.project_id;
      item.project_id = JSON.parse(item.project);
      item.months = moment(item.date_end)
        .add(1, 'days')
        .diff(moment(item.date_start), 'month');
    }

    return this.success(data);
  }

  async outputPutAction() {
    const values = this.post();
    let id = this.post('id');

    values.date_start = values.qixian[0];
    values.date_end = values.qixian[1];

    if (!think.isEmpty(values.project_id)) {
      // console.log(values);
      // const has = await this.model('contract_list')
      //   .where({ project_id: values.project_id, type: 2 })
      //   .find();
      // if (!think.isEmpty(has)) {
      //   return this.fail(401, '重复添加甲方合同');
      // }

      const months = moment(values.qixian[1])
        .add(1, 'days')
        .diff(moment(values.qixian[0]), 'month');
      if (!months) {
        return this.fail(401, '你的时间太短');
      }
      values.month = months;

      let ny = 0;

      if (values.nengyuan) {
        ny = BigNumber(values.nengyuan)
          .times(BigNumber(months))
          .times(BigNumber(values.area_contract))
          .toFixed(2);
      }

      const chengben = BigNumber(values.fangzu)
        .plus(BigNumber(values.wuye))
        .plus(BigNumber(ny))
        .div(BigNumber(values.area))
        .div(months || 1);

      for (const item of values.project_id) {
        if (item.length === 3) {
          const rooms = await this.model('project_list')
            .where({
              floor_id: item[2],
              type: 4,
            })
            .select();
          await this.model('project_list')
            .where({
              id: item[2],
            })
            .update({
              contract_time: values.qixian[0],
              contract_time_end: values.qixian[1],
            });
          for (const itemRoom of rooms) {
            const cost = BigNumber(chengben).times(BigNumber(itemRoom.area));
            await this.model('project_list')
              .where({
                id: itemRoom.id,
              })
              .update({
                chengben: cost.toFixed(2),
                average: chengben.toFixed(2),
              });
            if (!id && itemRoom.status == 0) {
              this.model('project_list')
                .where({
                  id: itemRoom.id,
                })
                .update({
                  status: 1,
                });
            }
          }
        }
      }
    }

    values.mianzu_start = values.mianzu[0];
    values.mianzu_end = values.mianzu[1];
    values.project = JSON.stringify(values.project_id);
    values.project_id = values.project_id[0][0];
    values.type = 2;

    if (id > 0) {
      await this.model('contract_list')
        .where({
          id: id,
        })
        .update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑甲方合同',
        content: id,
      });
    } else {
      // if (think.isEmpty(values.list)) {
      //   return this.fail(401, '缺少付款周期');
      // }
      delete values.id;
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];

      id = await this.model('contract_list').add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增甲方合同',
        content: id,
      });
      // this.model('custom').addData(values);
    }

    for (const item of values.list) {
      item.contract_id = id;
      item.project_id = values.project_id;
      item.account_id = null;
      item.status = 0;
      item.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      if (item.circle.length) {
        item.circle_start = item.circle[0];
        item.circle_end = item.circle[1];
      }
    }
    this.model('output_list').addMany(values.list);

    return this.success(values);
  }

  async importReloadAction() {
    // const list = await this.model('contract_list')
    //   .where({ type: 1 })
    //   .select();
    // for (const item of list) {
    //   const projectInfo = JSON.parse(item.project);
    //   const info = [];
    //   for (const itemInfo of projectInfo) {
    //     const origin = await this.model('project_list')
    //       .where({ id: itemInfo[3] })
    //       .find();
    //     info.push({
    //       origin_id: origin.origin_id,
    //       area: origin.area,
    //     });
    //   }

    //   await this.model('contract_list')
    //     .where({ id: item.id })
    //     .update({
    //       origin_info: JSON.stringify(info),
    //     });
    // }
    return this.success();
  }

  async importPutAction() {
    const values = this.post();
    const id = this.post('id');
    values.date_start = values.qixian[0];
    values.date_end = values.qixian[1];
    values.mianzu_start = values.mianzu[0];
    values.mianzu_end = values.mianzu[1];
    values.type = 1;
    // if (values.file && values.file.length) {
    //   values.file = JSON.stringify(values.file);
    // }

    if (values.project_id) {
      const projectInfo = values.project_id;
      const rooms = [];
      let chengben = BigNumber(0);

      values.floor_id = [];
      values.room_id = [];
      values.origin_info = [];
      for (const item of projectInfo) {
        values.floor_id.push(item[2]);
        values.room_id.push(item[3]);
        const origin = await this.model('project_list')
          .where({
            id: item[3],
          })
          .find();
        const originInfo = await this.model('project_list')
          .where({
            id: origin.origin_id,
          })
          .find();
        // .getField('origin_id', true);
        values.origin_info.push({
          origin_id: origin.origin_id,
          area: origin.area,
        });
        const roomChengben = BigNumber(originInfo.chengben_unit).times(
          BigNumber(origin.area)
        );
        chengben = chengben.plus(roomChengben);
        rooms.push(item[3]);
      }

      values.project = JSON.stringify(projectInfo);
      values.project_id = projectInfo[0][0];
      values.building_id = projectInfo[0][1];
      values.floor_id = values.floor_id.join(',');
      values.origin_info = JSON.stringify(values.origin_info);

      // const chengben = await this.model('project_list')
      //   .where({ id: ['IN', originId] })
      //   .sum('chengben');

      // const area = await this.model('project_list')
      //   .where({ id: ['IN', rooms] })
      //   .sum('area');

      const months = moment(values.qixian[1])
        .add(1, 'days')
        .diff(moment(values.qixian[0]), 'month');

      if (!months) {
        return this.fail(401, '你的时间太短');
      }

      values.month = months;

      values.chengben = BigNumber(chengben)
        .times(BigNumber(months))
        .toFixed(2);

      let ny = 0;

      if (values.nengyuan) {
        ny = BigNumber(values.nengyuan)
          .times(BigNumber(months))
          .times(BigNumber(values.area_contract))
          .toFixed(2);
      }

      const zujin = BigNumber(values.fangzu)
        .plus(BigNumber(values.wuye))
        .plus(BigNumber(ny))
        .div(BigNumber(values.area_contract))
        .div(months);

      const roomsData = await this.model('project_list')
        .where({
          id: ['IN', rooms],
        })
        .select();

      for (const item of roomsData) {
        const cost = BigNumber(zujin).times(BigNumber(item.area));
        this.model('project_list')
          .where({
            id: item.id,
          })
          .update({
            zujin: cost.toFixed(2),
            date_start: values.date_start,
            date_end: values.date_end,
          });
        if (!id) {
          this.model('project_list')
            .where({
              id: item.id,
            })
            .update({
              status: 2,
            });
        }
      }
    }

    if (id > 0) {
      delete values.status;
      await this.model('contract_list')
        .where({
          id: id,
        })
        .update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑租赁合同',
        content: id,
      });

      if (values.custom && values.custom.length) {
        this.model('contract_list')
          .where({
            id: id,
          })
          .update({
            custom_info: JSON.stringify(values.custom),
          });
      }
    } else {
      delete values.id;
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];

      const addId = await this.model('contract_list').add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新建租赁合同',
        content: addId,
      });
      if (values.custom && values.custom.length) {
        this.model('custom').addData(values.custom, addId);
        this.model('contract_list')
          .where({
            id: addId,
          })
          .update({
            custom_info: JSON.stringify(values.custom),
          });
      }
    }
    // if (values.list && values.list.length) {
    //   for (const item of values.list) {
    //     item.contract_id = id;
    //     item.project_id = values.project_id;
    //     item.account_id = null;
    //     item.status = 0;
    //     item.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
    //     if (item.circle.length) {
    //       item.circle_start = item.circle[0];
    //       item.circle_end = item.circle[1];
    //     }
    //     if (item.type === 'yajinShuidian') {
    //       item.type = 'yajin';
    //       item.yajin_type = 'yajinShuidian';
    //       item.yajin_type_str = '水电押金';
    //     } else if (item.type === 'yajinZhuangxiu') {
    //       item.type = 'yajin';
    //       item.yajin_type = 'yajinZhuangxiu';
    //       item.yajin_type_str = '装修押金';
    //     } else if (item.type === 'yajin') {
    //       item.yajin_type = 'yajin';
    //       item.yajin_type_str = '租赁押金';
    //     }
    //   }
    //   this.model('income_list').addMany(values.list);
    // }

    // if (values.shuidian && values.shuidian.length) {
    //   for (const item of values.shuidian) {
    //     item.contract_id = id;
    //     item.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
    //   }
    //   this.model('shuidian_list').addMany(values.shuidian);
    // }
    if (values.ac_list) {
      const acArr = values.ac_list.split(',');
      for (const item of acArr) {
        this.model('equipment_list')
          .where({
            id: item,
          })
          .update({
            contract_id: id,
          });
      }
    }

    return this.success(values);
  }

  async outputDetailAction() {
    const id = this.get('id');
    const list = await this.model('output_list')
      .where({
        contract_id: id,
      })
      .select();

    return this.success(list);
  }

  async zengzhiAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get();
    let order = ['custom DESC'];

    query.type = 3;
    if (!query.contract_type) {
      query.contract_type = ['!=', 63];
      order = ['contract_type DESC, date_start DESC'];
    }

    delete query.page;
    delete query.size;

    if (query.custom) {
      query.custom = ['like', `%${query.custom}%`];
    }
    if (query.remark) {
      query['remark|sale|remark_more'] = ['like', `%${query.remark}%`];
    }

    const data = await this.model('contract_list')
      .where(query)
      .order(order)
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      item.qixian = [item.date_start, item.date_end];
      item.project = [
        item.project_id,
        item.building_id,
        parseInt(item.floor_id),
        parseInt(item.room_id),
      ];
    }

    return this.success(data);
  }

  async zengzhiContractAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get();
    query.type = 4;

    delete query.page;
    delete query.size;

    const data = await this.model('contract_list')
      .where(query)
      .order(['id DESC'])
      .page(page, size)
      .countSelect();
    for (const item of data.data) {
      item.qixian = [item.date_start, item.date_end];
    }

    return this.success(data);
  }

  async putzengzhiContractAction() {
    const values = this.post();
    const id = this.post('id');
    values.type = 4;

    values.date_start = values.qixian[0];
    values.date_end = values.qixian[1];

    if (id > 0) {
      await this.model('contract_list')
        .where({
          id: id,
        })
        .update(values);

      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑增值合同child',
        content: id,
      });
    } else {
      delete values.id;
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];

      const addId = await this.model('contract_list').add(values);

      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新建增值合同child',
        content: addId,
      });
    }
    return this.success(values);
  }

  async zengzhiPutAction() {
    const values = this.post();
    const id = this.post('id');
    values.type = 3;

    if (values.qixian) {
      values.date_start = values.qixian[0];
      values.date_end = values.qixian[1];
    }

    if (values.project && values.project.length) {
      values.project_id = values.project[0];
      values.building_id = values.project[1];
      values.floor_id = values.project[2];
      values.room_id = values.project[3];
      values.project = JSON.stringify(values.project);
    }

    // if (values.file && values.file.length) {
    //   values.file = JSON.stringify(values.file);
    // }

    if (id > 0) {
      await this.model('contract_list')
        .where({
          id: id,
        })
        .update(values);

      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑增值合同',
        content: id,
      });
    } else {
      delete values.id;
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];

      const addId = await this.model('contract_list').add(values);
      // this.model('custom').addData(values);

      if (values.contract_type === 70 || values.contract_type === 122) {
        this.model('guakao_list').add({
          contract_id: addId,
          create_time: ['exp', 'CURRENT_TIMESTAMP()'],
          start: values.date_start,
          end: values.date_end,
          room_id: values.room_id,
          custom_name: values.custom,
          sale: values.sale,
          remark: values.remark,
          money: values.money,
        });
      }
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新建增值合同',
        content: addId,
      });
    }
    return this.success(values);
  }

  async detailAction() {
    const data = await this.model('contract_list')
      .where({
        id: this.get('contract_id'),
      })
      .find();
    if (data.file) {
      data.file = JSON.parse(data.file);
    }
    data.qixian = [data.date_start, data.date_end];
    data.mianzu = [data.mianzu_start, data.mianzu_end];
    data.project_id = JSON.parse(data.project);
    if (data.custom_info) {
      data.custom = JSON.parse(data.custom_info);
    }
    return this.success(data);
  }

  async closeAction() {
    const data = await this.model('contract_list')
      .where({
        id: this.post('id'),
      })
      .update({
        status: 3,
        tuizuTxt: this.post('remark'),
        tuizuDate: this.post('tuizuDate'),
      });

    const info = await this.model('contract_list')
      .where({
        id: this.post('id'),
      })
      .find();

    // if (info.type === 1) {
    //   const projectInfo = JSON.parse(info.project);
    //   for (const item of projectInfo) {
    //     const rooms = await this.model('project_list')
    //       .where({
    //         id: item[3],
    //       })
    //       .update({
    //         status: 1,
    //       });
    //   }
    // }

    if (info.type === 2) {
      this.model('output_list')
        .where({
          contract_id: info.id,
        })
        .update({
          tuizu: 1,
        });
      // 处理甲方合同 将房源状态设置为空闲
      const projectInfo = JSON.parse(info.project);
      for (const item of projectInfo) {
        await this.model('project_list')
          .where({
            floor_id: item[2],
          })
          .update({
            status: 0,
          });
      }
    } else {
      this.model('income_list')
        .where({
          contract_id: info.id,
        })
        .update({
          tuizu: 1,
        });
    }

    return this.success(data);
  }

  async delZengzhiContractAction() {
    await this.model('contract_list')
      .where({
        id: this.get('id'),
        type: 4,
      })
      .delete();

    return this.success();
  }

  async contractEndAction() {
    const info = await this.model('contract_list')
      .where({
        id: this.get('id'),
      })
      .find();
    if (think.isEmpty(info)) {
      return this.fail(401, '找不到合同');
    }
    if (think.isEmpty(info.project)) {
      return this.fail(401, '找不到合同信息');
    }
    const projectInfo = JSON.parse(info.project);
    for (const item of projectInfo) {
      const rooms = await this.model('project_list')
        .where({
          floor_id: item[2],
        })
        .select();
      for (const roomItem of rooms) {
        if (roomItem.status === 2) {
          return this.fail(
            401,
            '该合同下还有房源处于在租状态, 如有疑问请联系管理员'
          );
        }
      }
    }

    const list = await this.model('output_list')
      .where({
        contract_id: this.get('id'),
        type: 'yajin',
      })
      .select();

    return this.success(list);
  }

  async closeDoorAction() {
    const id = this.post('id');
    const info = await this.model('contract_list')
      .where({
        id: id,
      })
      .find();
    if (think.isEmpty(info)) {
      return this.fail(401, '找不到合同');
    }
    if (think.isEmpty(info.project)) {
      return this.fail(401, '找不到合同信息');
    }
    const projectInfo = JSON.parse(info.project);
    for (const item of projectInfo) {
      const room = await this.model('project_list')
        .where({
          id: item[3],
        })
        .find();

      if (room && room.permId) {
        const users = await this.service('menjin').getUser(room.permId);
        if (users && users.length) {
          const userInfo = [];
          for (const item of users) {
            userInfo.push({
              pin: item.pin,
              startTime: moment()
                .subtract(1, 'year')
                .format('YYYY-MM-DD HH:mm:ss'),
              endTime: moment()
                .subtract(1, 'hour')
                .format('YYYY-MM-DD HH:mm:ss'),
            });
          }
          await this.service('menjin').shatdown(userInfo);
        }
      }
    }
    return this.success();
  }
  async openDoorAction() {
    const id = this.post('id');
    const info = await this.model('contract_list')
      .where({
        id: id,
      })
      .find();
    if (think.isEmpty(info)) {
      return this.fail(401, '找不到合同');
    }
    if (think.isEmpty(info.project)) {
      return this.fail(401, '找不到合同信息');
    }
    const projectInfo = JSON.parse(info.project);
    for (const item of projectInfo) {
      const room = await this.model('project_list')
        .where({
          id: item[3],
        })
        .find();

      if (room && room.permId) {
        const users = await this.service('menjin').getUser(room.permId);
        if (users && users.length) {
          const userInfo = [];
          for (const item of users) {
            userInfo.push({
              pin: item.pin,
              startTime: moment()
                .subtract(1, 'days')
                .format('YYYY-MM-DD HH:mm:ss'),
              endTime: moment()
                .add(10, 'years')
                .format('YYYY-MM-DD HH:mm:ss'),
            });
          }
          await this.service('menjin').shatdown(userInfo);
        }
      }
    }
    return this.success();
  }
};
